package edu.nf.exam.service.impl;

import com.github.pagehelper.PageInfo;
import edu.nf.exam.dao.UserInfoDao;
import edu.nf.exam.dao.impl.UserInfoDaoImpl;
import edu.nf.exam.entity.UserInfo;
import edu.nf.exam.exception.DataAcessException;
import edu.nf.exam.exception.LoginException;
import edu.nf.exam.service.UserService;

import java.util.List;

/**
 * @Author : PYY
 * @create 2021/6/17
 */
public class UserServiceImpl implements UserService {
    @Override
    public UserInfo checkUser(UserInfo user) {
        //根据用户名先从数据库查询用户信息
        UserInfoDao dao = new UserInfoDaoImpl();
        UserInfo u = dao.getUserByName(user.getUserName());

        //校验用户名、密码和状态，如果用户不为空，就验证密码，密码正确就验证账号状态
        if(u != null){
            //验证密码和状态
            if(!user.getPassword().equals(u.getPassword())){
                throw new LoginException("用户名或密码错误");
            }else if(u.getStatus()!=1){
                throw new LoginException("账号异常，限制登录");
            }
            return u ;
        }
        throw new LoginException("用户名或密码错误");
    }

    /**
     * 多条件查询用户
     * @param userInfo
     * @return
     */
    @Override
    public List<UserInfo> select(UserInfo userInfo) {
        List<UserInfo> list = new UserInfoDaoImpl().select(userInfo);
        return list;
    }

    /**
     * 注册认证
     * @param user
     * @return
     */
    @Override
    public int checkRegister(UserInfo user) {
        //根据用户名先查询数据库用户信息
        UserInfoDao dao = new UserInfoDaoImpl();
        UserInfo u = dao.getUserByName(user.getUserName());

        //账号判断
        if(u==null){
            int r = dao.register(user);
            if(r==1){
                return r;
            }else{
                throw new LoginException("注册失败");
            }
        }
        throw new LoginException("用户已存在");
    }

    /**
     * 用户修改信息认证
     * @param userInfo
     * @return
     */
    @Override
    public void checkUpdate(UserInfo userInfo) {
        try {
            UserInfoDao dao=new UserInfoDaoImpl();
            dao.update(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DataAcessException("更新失败");
        }
    }

    /**
     * 分页查询
     * @param userId
     * @param userName
     * @param role
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<UserInfo> listUserInfo(Integer userId, String userName, Integer role, Integer pageNum, Integer pageSize) {
        List<UserInfo> list = new UserInfoDaoImpl().listUserInfo(userId,userName,role,pageNum,pageSize);
        PageInfo<UserInfo> pageInfo = new PageInfo(list);
        return pageInfo;
    }

}
